package org.hxyjs.service.impl;


import org.hxyjs.vo.MailUser;
import org.hxyjs.service.MailSendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Service
public class MailSendServiceImpl implements MailSendService {

   	@Resource
	private JavaMailSender javaMailSender;
	@Autowired
	private Environment env;


//从env 环境得到 配置文件的值
	public String getUsername() {
		return env.getProperty("spring.mail.username");
	}

	/**
   	 * 发送邮件
   	 */
   	@Override
   	public void sendMail(MailUser mailUser, String subject, String mailDetail) {
//   		SimpleMailMessage message = new SimpleMailMessage();
//		message.setFrom(username);
//		//收件人邮箱
//           message.setTo(mailUser.getMailAddress());
//           message.setSubject(mailUser.getMailName());
//           //这里暂时已用户名作为发送的内容
//           message.setText(mailDetail);
//           mailSender.send(message);
		MimeMessage mimeMailMessage = null;
			mimeMailMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper mimeMessageHelper = null;
			try {
				mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true,"UTF-8");
				mimeMessageHelper.setFrom(getUsername());// 发件人地址
				mimeMessageHelper.setTo(mailUser.getMailAddress());//收件人地址
				mimeMessageHelper.setSubject(subject);//邮件标题
				mimeMessageHelper.setText(mailDetail, true);
				mimeMessageHelper.setSentDate(new Date());
				javaMailSender.send(mimeMailMessage);
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
   }